<script setup lang="ts">
import UserCard from "./components/userCard.vue"
import { useSettingsStore } from "@/store/modules/settings"
import { onMounted, onUnmounted, ref, nextTick } from "vue"
import { useIntersectionObserver } from "@vueuse/core"
import ArticleCard from "./components/articleCard.vue"
import { getRecommendArticleAPI } from "@/api/web/article"
import { useRouter } from "vue-router"
import IndexBg from "./components/IndexBg.vue"
import TypeWrite from "./components/TypeWrite.vue"
import {ArticleItem} from "@/types/admin/article"
import { gsap } from "gsap"
import { ScrollTrigger } from "gsap/ScrollTrigger"

// 注册GSAP插件
gsap.registerPlugin(ScrollTrigger)

const VITE_APP_TITLE = import.meta.env.VITE_APP_TITLE

// 全局路由对象
const router = useRouter()

// 设置对象
const settings = useSettingsStore()

// 改变导航栏背景显示
const changeNavBg = (value: boolean) => {
  settings.changeNavBg(value)
}

// 元素进入视口渐入
const articleTarget = ref<any>(null)
const targetIsActive = ref<boolean>(false)

// 进入视口修改激活状态
const { stop } = useIntersectionObserver(articleTarget, ([{ isIntersecting }]) => {
  targetIsActive.value = isIntersecting
})

// 推荐文章列表
const recommendArticleList = ref<ArticleItem[]>([])

// 获取推荐文章
const getRecommendArticle = async () => {
  const res = await getRecommendArticleAPI()
  // console.log(res)

  if (res.code === 200) {
    recommendArticleList.value = res.data as ArticleItem[]
    // 等待DOM更新后执行动画
    await nextTick()
    initGSAPAnimations()
  }
}

// 初始化GSAP动画
const initGSAPAnimations = () => {
  // 主内容区动画
  gsap.fromTo(".main-content",
    {
      opacity: 0,
      y: 100,
      scale: 0.9
    },
    {
      opacity: 1,
      y: 0,
      scale: 1,
      duration: 1.2,
      ease: "back.out(1.7)",
      scrollTrigger: {
        trigger: ".main-content",
        start: "top 80%",
        end: "bottom 20%",
        toggleActions: "play none none reverse"
      }
    }
  )

  // 文章标题区动画
  gsap.fromTo(".article-title-section",
    {
      opacity: 0,
      x: -50,
      rotationX: -15
    },
    {
      opacity: 1,
      x: 0,
      rotationX: 0,
      duration: 0.8,
      ease: "power2.out",
      scrollTrigger: {
        trigger: ".article-title-section",
        start: "top 85%",
        toggleActions: "play none none reverse"
      }
    }
  )

  // 文章卡片动画 - 交错动画
  gsap.fromTo(".article-card",
    {
      opacity: 0,
      y: 60,
      rotationY: -15,
      scale: 0.8
    },
    {
      opacity: 1,
      y: 0,
      rotationY: 0,
      scale: 1,
      duration: 0.8,
      ease: "power2.out",
      stagger: {
        amount: 0.6,
        from: "start"
      },
      scrollTrigger: {
        trigger: ".articles-grid",
        start: "top 80%",
        toggleActions: "play none none reverse"
      }
    }
  )

  // 右侧边栏动画
  gsap.fromTo(".sidebar-content",
    {
      opacity: 0,
      x: 100,
      scale: 0.9
    },
    {
      opacity: 1,
      x: 0,
      scale: 1,
      duration: 1,
      ease: "elastic.out(1, 0.5)",
      scrollTrigger: {
        trigger: ".sidebar-content",
        start: "top 85%",
        toggleActions: "play none none reverse"
      }
    }
  )

  // 添加悬停动画
  const articleCards = document.querySelectorAll('.article-card')
  articleCards.forEach(card => {
    card.addEventListener('mouseenter', () => {
      gsap.to(card, {
        y: -10,
        scale: 1.03,
        boxShadow: "0 20px 40px rgba(0,0,0,0.15)",
        duration: 0.3,
        ease: "power2.out"
      })
    })

    card.addEventListener('mouseleave', () => {
      gsap.to(card, {
        y: 0,
        scale: 1,
        boxShadow: "0px 2px 20px #999",
        duration: 0.3,
        ease: "power2.out"
      })
    })
  })
}

// 查看更多
const showMore = () => {
  router.push("/home-article")
}

// 点击划入主内容区
const scrollIndex = () => {
  window.scrollTo({
    top: articleTarget.value?.offsetTop - 80,
    behavior: "smooth"
  })
}
onMounted(() => {
  changeNavBg(false)
  getRecommendArticle()
})

onUnmounted(() => {
  changeNavBg(true)
  stop()
  // 清理所有GSAP动画和ScrollTrigger
  ScrollTrigger.getAll().forEach(trigger => trigger.kill())
  gsap.killTweensOf("*")
})
</script>

<template>
  <div class="index" :class="{ mobile: settings.isMobile }">
    <IndexBg />
    <div class="index-title animate__lightSpeedInRight animate__animated ">
      <h1>{{ VITE_APP_TITLE }}</h1>
      <TypeWrite />
      <div class="icon">
        <el-icon :size="30" color="#fff" @click="scrollIndex"><ArrowDownBold /></el-icon>
      </div>
    </div>
    <!-- 主内容区 -->
    <div ref="articleTarget" class="main-content container mx-auto max-w-screen-xl mt-5" :class="{ active: targetIsActive || settings.isMobile }">
      <div class="content-wrapper">
        <!-- 左边栏 -->
        <div class="articles-section">
          <div class="article-title-section">
            <div class="title-content">
              <div class="title-icon">
                <SvgIcon name="article" />
              </div>
              <h4 class="text-black dark:text-white">✨ 精选文章</h4>
            </div>
            <button class="more-btn" @click="showMore">
              <span>查看更多</span>
              <svg class="arrow-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M5 12h14M12 5l7 7-7 7"/>
              </svg>
            </button>
          </div>
          <!-- 文章列表 -->
          <div class="articles-grid">
            <div v-for="item in recommendArticleList" :key="item._id" class="article-card-wrapper">
              <ArticleCard :article="item" class="article-card" />
            </div>
          </div>
        </div>

        <!-- 右边栏 -->
        <div class="sidebar">
          <div class="sidebar-content sticky top-21">
            <UserCard />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.index {
  font-size: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;

  &.mobile {
    font-size: 16px;
  }

  // 让标题区域固定高度
  .index-title {
    flex-shrink: 0;
  }

  // 让主内容区域占据剩余空间
  .main-content {
    flex: 1;
    min-height: 0; // 重要：让flex子项能够正确收缩
  }
}

.index-title {
  width: 100%;
  height: calc(100vh - 60px);
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  color: #fff;
  position: relative;

  h1 {
    font-size: 3.5em;
    font-weight: 800;
    letter-spacing: 5px;
    font-family: "STKaiti";
  }

  .icon {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    animation: twinkle 0.7s linear infinite alternate;

    .el-icon {
      cursor: var(--cursor-pointer);
    }

    svg {
      cursor: var(--cursor-pointer);
    }
  }

  @keyframes twinkle {
    to {
      opacity: 0.5;
      transform: scale(0.9) translateY(0) translateX(-50%);
    }
    from {
      opacity: 1;
      transform: scale(1) translateY(-10px) translateX(-50%);
    }
  }
}

// 主内容区样式
.main-content {
  max-width: 1230px;
  opacity: 0;
  transform: translateY(100px);
  transition: all 0.5s;
  padding: 20px;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;

  &.active {
    opacity: 1;
    transform: translateY(0);
  }
}

.content-wrapper {
  display: grid;
  grid-template-columns: 1fr 350px;
  gap: 40px;

  @media (max-width: 1024px) {
    grid-template-columns: 1fr;
    gap: 30px;
  }
}

.articles-section {
  width: 100%;
}

// 文章标题区域美化
.article-title-section {
  background: var(--gradient-primary);
  margin-bottom: 30px;
  border-radius: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25px 30px;
  box-shadow:
    0 20px 40px rgba(102, 126, 234, 0.15),
    0 0 0 1px rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;

  // 背景装饰
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background:
      radial-gradient(circle at 20% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
      radial-gradient(circle at 80% 80%, rgba(255, 255, 255, 0.05) 0%, transparent 50%);
    pointer-events: none;
  }

  .title-content {
    display: flex;
    align-items: center;
    gap: 15px;
    position: relative;
    z-index: 1;

    .title-icon {
      width: 50px;
      height: 50px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
      backdrop-filter: blur(10px);

      :deep(svg) {
        width: 24px;
        height: 24px;
        color: white;
      }
    }

    h4 {
      font-size: 24px;
      font-weight: 700;
      color: white !important;
      text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
      margin: 0;
    }
  }

  .more-btn {
    background: rgba(255, 255, 255, 0.2);
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: 50px;
    padding: 12px 25px;
    color: white;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    backdrop-filter: blur(10px);
    position: relative;
    z-index: 1;

    &:hover {
      background: rgba(255, 255, 255, 0.3);
      border-color: rgba(255, 255, 255, 0.5);
      transform: translateY(-2px);
      box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);

      .arrow-icon {
        transform: translateX(3px);
      }
    }

    .arrow-icon {
      width: 16px;
      height: 16px;
      transition: transform 0.3s ease;
    }
  }
}

// 文章网格布局
.articles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 30px;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 20px;
  }
}

.article-card-wrapper {
  perspective: 1000px;
}

// 右侧边栏样式
.sidebar {
  @media (max-width: 1024px) {
    order: -1;
  }
}

.sidebar-content {
  position: sticky;
  top: 80px;
}

// 响应式设计
@media (max-width: 1024px) {
  .content-wrapper {
    padding: 0 15px;
  }

  .article-title-section {
    padding: 20px;
    border-radius: 15px;

    .title-content h4 {
      font-size: 20px;
    }

    .more-btn {
      padding: 10px 20px;
      font-size: 14px;
    }
  }

  .main-content {
    margin-bottom: 30px;
  }
}

@media (max-width: 768px) {
  .article-title-section {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }

  .articles-grid {
    gap: 15px;
  }

  .main-content {
    margin-bottom: 20px;
  }
}

// 原有样式保留
.sticky {
  position: sticky;
  top: 60px;
}

.article-img {
  width: 100%;
}

.two-line-clamp {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.el-menu--horizontal .el-menu-item:not(.is-disabled):focus,
.el-menu--horizontal .el-menu-item:not(.is-disabled):hover {
  outline: 0;
  color: var(--el-menu-text-color);
  background-color: #fff;
  border-bottom: 2px solid #409eff;
}

.category-item:hover {
  text-decoration: underline;
  cursor: var(--cursor-pointer) 50 50, pointer !important;
}

.tag-item:hover {
  cursor: var(--cursor-pointer) 50 50, pointer !important;
}

.el-tag:hover {
  background-color: var(--el-color-info-light-8);
}


// 确保页面内容完全可见，底部不被截断
// 移除可能冲突的样式，让flex布局正常工作
</style>
